package com.appspot.didit.client.tag;

import java.util.ArrayList;

import com.extjs.gxt.ui.client.event.*;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.*;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;

public class TagShareView extends Composite implements TagSharePresenter.View {
	private final TagServiceAsync tagService = GWT.create(TagService.class);
	public final Label shareHint;
	
	public final Label usernameLabel;
	
	public final TextBox usernameTb;
	
	public final Label tagLabel;
	
	public final TextBox tagTb;
	
	public final Label userlistLabel;
	
	public final ListBox userlistLb;
	
	public final FlexTable userlistFt;
	
	public final Button shareButton;
	
	public ArrayList<Button> delButton;
	
    @SuppressWarnings("unchecked")
	public TagShareView() {

    	shareHint = new Label();
    	delButton = new ArrayList<Button>();
    	
    	tagLabel  = new Label("Projekt:");
    	tagTb = new TextBox();
        tagTb.setReadOnly(true);
        tagTb.addFocusHandler(new FocusHandler() {
			public void onFocus(FocusEvent event) {
				TagCloud tc = TagManager.getInstance().getTagCloud();
				if(tc != null && !tc.isShowing()) {
					tc.show(tagTb);
				}
			}
		});
        tagTb.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				tagTb.setStyleName("");
			}
		});
        tagTb.addValueChangeHandler(new ValueChangeHandler() {
			@Override
			public void onValueChange(ValueChangeEvent event) {
				update();
			}
        });
        tagTb.addKeyDownHandler(new KeyDownHandler() {
			@Override
			public void onKeyDown(KeyDownEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_TAB) {
					 TagCloud tc = TagManager.getInstance().getTagCloud();
						if(tc != null && tc.getPartner().equals(tagTb)) {
							tc.hide();
						}
				 }
			}
        	
        });
        userlistLabel = new Label("Liste von Benutzern");
        userlistLb = new ListBox(true);
        userlistFt = new FlexTable(); 
        
        usernameLabel = new Label("Benutzername oder Emailadresse, mit ',' zu trennen:");
        usernameTb = new TextBox();
        
        shareButton = new Button("Freigeben");
        
        FlexTable layout = new FlexTable();
        layout.setCellSpacing(6);

        // Add some standard form options
        layout.setWidget(0, 0, shareHint);
        layout.setWidget(1, 0, tagLabel);
        layout.setWidget(1, 1, tagTb);
        layout.setWidget(2, 0, userlistLabel);
        layout.setWidget(2, 1, userlistFt);
        layout.setWidget(3, 0, usernameLabel);
        layout.setWidget(3, 1, usernameTb);
        layout.setWidget(4, 0, shareButton);
        initWidget(layout);
    }

    public Widget getWidget() {
            return this;
    }

	public void reset() {
		
	}
	
	public HasClickHandlers getShareClickHandlers() {
		return shareButton;
	}
	
	public HasText getShareHint() {
		return shareHint;
	}
	
	public HasValue<String> getTag() {
		return tagTb;
	}


	public HasValue<String> getUsername() {
		return usernameTb;
	}
	
	public void update() {
		userlistFt.clear();
		if(!tagTb.getValue().equals("")) {
			if(tagTb.getValue().contains(" ")) {
				tagTb.setValue(tagTb.getValue().substring(tagTb.getValue().lastIndexOf(" ") + 1));
			}
			final Tag t = TagManager.getInstance().myTagNameIndex.get(tagTb.getValue());
			int row = 0;
			delButton.clear();
			for(String username : t.getUsernames()) {
				final Button bt = new Button(username);
				bt.addClickHandler(new ClickHandler() {

					@Override
					public void onClick(ClickEvent event) {
						final Listener<MessageBoxEvent> l = new Listener<MessageBoxEvent>() {  
						      public void handleEvent(MessageBoxEvent ce) {  
						        if(ce.getButtonClicked().getText().equals("Yes")) {
						        	t.delUsername(bt.getText());
									tagService.withdrawShare(t.getId(), bt.getText(), new AsyncCallback() {
					                    		 public void onFailure(Throwable caught) {
									                    GWT.log("Failed to check the Validity of Username, Exception thrown", caught);
									                }

									                public void onSuccess(Object result) {
									                	update();
									                	GWT.log("Tag updated!", null);
									                }
					                    	});
						        } 
						      }  
						    };  
						MessageBox.confirm("Confirm", "Wollen Sie den Zugang zur\u00fccknehmen?", l);
					}
				});
				delButton.add(bt);
				userlistFt.setWidget(row++, 0, bt);
			}
		}
	}

}
